#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-11 下午2:46
from flask import Flask, Response, stream_with_context

app = Flask(__name__)

rows = ["abc", "def"]


def stream_template(template_name, **context):
    app.update_template_context(context)
    t = app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    rv.enable_buffering(5)
    return rv


# 这是使用jinja实现的
@app.route('/', methods=['GET'])
def index():
    return Response(stream_template("index.html", rows=rows))


# 这是使用flask内置支持
@app.route('/stream')
def index2():
    def generate():
        for row in rows:
            yield row

    return Response(stream_with_context(generate()))


if __name__ == '__main__':
    app.run(debug=True)